<template>
  <div class="qt-select">
    <qt-input
      type="text"
      :label="label"
      :value="value"
      :readonly="true"
      :required="required"
      :field-name="fieldName"
      :placeholder="placeholder"
      @click="handleClick"
    />
    <van-popup
      v-model="showPicker"
      position="bottom"
      :close-on-click-overlay="false"
      @click-overlay="closePick"
    >
      <van-datetime-picker
        :type="type"
        :value="value ? new Date(value) : new Date()"
        :title="placeholder"
        :formatter="formatter"
        @cancel="closePick"
        @confirm="onConfirmDate"
      />
    </van-popup>
  </div>
</template>

<script>
import QtInput from '../input';

export default {
  name: 'qt-date',

  components: {
    QtInput,
  },

  props: {
    label: String,

    type: String,

    value: [String, Date],

    required: {
      type: Boolean,
      default: false,
    },

    disabled: {
      type: Boolean,
      default: false,
    },

    fieldName: {
      type: String,
      default: '',
    },

    placeholder: {
      type: String,
      default: `请选择`,
    },
  },

  data() {
    return {
      showPicker: false,
      currentDate: this.value,
    };
  },

  methods: {
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`;
      } else if (type === 'month') {
        return `${val}月`;
      } else if (type === 'day') {
        return `${val}日`;
      } else if (type === 'hour') {
        return `${val}时`;
      } else if (type === 'minute') {
        return `${val}分`;
      }
      return val;
    },

    handleClick() {
      if (!this.disabled) {
        this.showPicker = true;
      }
    },

    closePick() {
      if (this.required && !this.currentDate) {
        return this.$toast.fail(`${this.label}不能为空！`);
      }
      this.showPicker = false;
    },

    onConfirmDate(value) {
      this.currentDate = value;
      if (this.type === 'date') {
        this.currentDate = this.$moment(value).format('YYYY-MM-DD');
      } else if (this.type === 'datetime') {
        this.currentDate = this.$moment(value).format('YYYY-MM-DD HH:mm');
      }
      this.$emit('change', this.currentDate, this.fieldName);
      this.closePick();
    },
  },
};
</script>
